﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.Revit;
using YJKArchUtils.Utils;
using YJKRevitView;

namespace YJKRevitArea.AreaSet
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdMergeFireZone : IExternalCommand
	{
		Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			CmdViewType types = CmdViewType.AreaPlan;
			if (SwitchView.SetUsableView(types, commandData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			List<Area> list = Common.FilterFireAreas(commandData.Application.ActiveUIDocument.Document);
			if (list.Count < 1)
			{
				YJKMessageBox.Show("该命令仅运行于存在防火分区面积的平面。");
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Dictionary<FireZoneInfo, List<Area>> dictionary = new Dictionary<FireZoneInfo, List<Area>>();
			this.SortAreaByName(ref dictionary, list);
			if (dictionary.Count == 0)
			{
				YJKMessageBox.Show("不存在可以合并的防火分区。");
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			HideWarningAndErroringKit @object = new HideWarningAndErroringKit(new List<string>
			{
				"Merge FireZone By Curves"
			}, HideWarningAndErroringKit.HideKitEnum.HideWarning);
			commandData.Application.Application.FailuresProcessing += @object.OnFailuresProcessing;
			if (!new MergeFireZone(commandData, dictionary).SolveGroupedArea())
			{
				YJKMessageBox.Show("合并防火分区失败。");
				return Autodesk.Revit.UI.Result.Failed;
			}
			YJKMessageBox.Show("完成防火分区的合并。");
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void SortAreaByName(ref Dictionary<FireZoneInfo, List<Area>> NamedSortArea, List<Area> areas)
		{
			Dictionary<FireZoneInfo, List<Area>> dictionary = new Dictionary<FireZoneInfo, List<Area>>();
			foreach (Area area in areas)
			{
				FireZoneInfo key = new FireZoneInfo
				{
					m_prefix = area.GetParameter("区域前缀").AsString(),
					m_name = area.get_Parameter(BuiltInParameter.ROOM_NAME).AsString(),
					m_number = area.GetParameter("区域编号").AsString(),
					m_suffix = area.GetParameter("区域后缀").AsString(),
					m_remark = area.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString()
				};
				if (dictionary.ContainsKey(key))
				{
					List<Area> list = dictionary[key];
					list.Add(area);
					dictionary[key] = list;
				}
				else
				{
					dictionary.Add(key, new List<Area>
					{
						area
					});
				}
			}
			foreach (KeyValuePair<FireZoneInfo, List<Area>> keyValuePair in dictionary)
			{
				if (keyValuePair.Value.Count > 1)
				{
					NamedSortArea.Add(keyValuePair.Key, keyValuePair.Value);
				}
			}
		}
	}
}
